#!/bin/bash
do_rke2_env()
{
    # Check if the rke2 env have configured
    if command -v kubectl &> /dev/null; then
        echo "rke2 env have configured"
        return
    fi
   
    # Check if the rke2.sh file exists in the current directory
    if [ ! -f "./rke2.sh" ]; then
        echo "Error: rke2.sh file not found in the current directory."
        exit 1
    fi

    # Check if the rke2.sh file exists in the /etc/profile.d/ directory
    if [ ! -f "/etc/profile.d/rke2.sh" ]; then
        # Copy the rke2.sh file to the /etc/profile.d/ directory
        cp ./rke2.sh /etc/profile.d/
    fi

    # Execute the source /etc/profile.d/rke2.sh command
    . /etc/profile.d/rke2.sh

    # Output a message indicating that the rke2.sh environment variables were configured successfully
    echo "rke2.sh environment variables configured successfully."
}


do_apply_branding()
{
    CONFIG_FILE="/etc/rancher/rancherd/config.yaml"
    BRANDING_FILE="./post_config/branding.yaml"
    
    # Check if the config file exists
    if [ ! -f "$CONFIG_FILE" ]; then
        echo "Error: Rancherd config file $CONFIG_FILE not found. This may not a harvester cluster."
        echo "Error: Can't apply branding config."
        exit 1
    fi
    
    # Check if this node is cloud-init node'
    if yq e '.role' "$CONFIG_FILE" | grep -q "cluster-init"; then
        echo "This node is a cluster-init node."
        # Check if the branding file exists
        if [ ! -f "$BRANDING_FILE" ]; then
            echo "Error: Branding file $BRANDING_FILE not found."
            return 1
        fi
        # Apply the branding configuration
        kubectl apply -f "$BRANDING_FILE"
        if [ $? -eq 0 ]; then
            echo "Branding applied successfully."
        else
            echo "Error: Failed to apply branding."
            return 1
        fi
    else
        echo "This node is an Agent node. No need to exec branding in this node."
    fi
}

do_rke2_env

do_apply_branding
